#!/usr/bin/env python
from google.appengine.ext import db

def isOwner(course):
    owner = GeneralM.getEmail()
    if owner == course.owner:
        return True;
    elif db.Query(InviteM.Ownership).filter('owner =', owner).filter('course =', course).count() > 0:
        return True;
    else:
        return False;

def addCourse(name):
    owner = GeneralM.getEmail()
    name=name.strip()
    if not owner:
        return 'error: user is not logged in'
    elif name == '':
        return 'error: Course name empty'
    elif db.Query(Course).filter('name =', name).filter('owner =', owner).count() > 0:
        return 'error: Course name exists'
    else:
        course = Course(name = name, owner = owner)
        course.put()
        return course
 
def getCourses():
    owner = GeneralM.getEmail()
    if owner:
        return list(db.Query(Course).filter('owner =', owner).filter('deleted =',False)) + getCoursesByOwnership()
                
    else:
        pass

#Getting courses that are shared with you
def getCoursesByOwnership():
    owner = GeneralM.getEmail()
    if owner:
        return map(getByOwnershipHelper, list(db.Query(InviteM.Ownership).filter('owner =', owner)))

def getByOwnershipHelper(ownership):
    return ownership.course;

def getCourseByKey(key):
    owner = GeneralM.getEmail()
    if owner and key:
            course = Course.get(key)
            if isOwner(course):
                return course
            else:
                return 'error:user accessed course key or another user'

def course2Dict(course, withLectures = 0):
    if withLectures:
        lectures = map(LectureM.lecture2Dict, LectureM.getLecturesByCourse(course))
    else:
        lectures = None
    courseDic = {
               'key' : course.key(),
               'name' : course.name,
               'lectures' : lectures
           }
    return courseDic

def course2DictWith(course):
    return course2Dict(course, 1)

class Course(db.Model):
    owner=db.StringProperty()
    name=db.StringProperty()
    deleted=db.BooleanProperty(default=False)
    
import GeneralM
import LectureM
import InviteM